#pragma once

#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>

// #define MySelf 1

const std::string blank_space_sep = " ";
const std::string protocol_sep = "\n";
using namespace std;
//"len\n\x op y\n"
std::string Encode(string& content)//加报头
{
    int a=content.size();
    string s=to_string(a);
    s+=protocol_sep;
    s+=content;
    s+=protocol_sep;  
    return s;
}
//"x op y"
bool Decode(string&package,string&content)
{
    size_t pos=package.find(protocol_sep);
    if(pos==std::string::npos) return false;
    string len_str=package.substr(0,pos);
    size_t total_len=len_str.size()+stoi(len_str)+2;
    if(package.size() < total_len) return false;
    content=package.substr(pos+1,stoi(len_str));//从pos+1  位置开始，取len的长度，x op y
    package.erase(0,total_len);//移除报文，接收多个时移除
    return true;
}
class request
{
public:
    request(int data1, int data2, char oper)  : x(data1), y(data2), op(oper)
    {
    }
    request()
    {}
    ~request()
    {
    }
     void DebugPrint()
    {
        std::cout << "新请求构建完成:  " << x << op << y << "=?" << std::endl;
    }
public:
    bool Serialize(string& out)//序列化,结构体变成字符串"x op y"
    {
        string s=to_string(x);
        s+=blank_space_sep;
        s+=op;     
        s+=blank_space_sep;
        s+=to_string(y);
        out=s;
        return true;
    }
    bool DSerialize(const string& in)//饭序列化,字符串变结构体,传进来"x op y"
    {
        size_t left=in.find(blank_space_sep);
        string part_x=in.substr(0,left);
        op=in[left+1];
        size_t right=in.rfind(blank_space_sep);
        string part_y=in.substr(right+1);
        if(left+2!=right) return false;
        x=stoi(part_x);
        y=stoi(part_y);
        return true;
    }
public:
    int x;
    int y;
    char op;
};

class response
{
public:
    response(int res,int c):result(res),code(c)
    {
    }
    response()
    {

    }
    ~response()
    {
    }
public:
//"result code"
    bool Serialize(string& out)
    {
        string s=to_string(result);
        s+=blank_space_sep;
        s+=to_string(code);
        out=s;
        return true;
    }
    bool DSerialize(string& in)
    {
        size_t pos=in.find(blank_space_sep);
        if(pos==std::string::npos) return false;
        string part_result=in.substr(0,pos);
        string part_code=in.substr(pos+1);
        result=stoi(part_result);
        code=stoi(part_code);
        return true;
    }
    void DebugPrint()
    {
        std::cout << "结果响应完成, result: " << result << ", code: "<< code << std::endl;
    }
public:
    int result;
    int code;
};